using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using hpcpdi.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace hpcpdi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        [HttpPost("/api/account/login")]
        public IActionResult login(string username, string password)
        {
            //实际项目中，此处可改为从 据库查询
            if (username == "admin" && password == "admin888")
            {
                //有效载荷，可以自定义，想写多少写多少，尽量避免敏感信息
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name,username),
                    new Claim(ClaimTypes.Role,"1"),
                    new Claim("grade","2"),

                    new Claim(JwtRegisteredClaimNames.Sub,"subName"),
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),//NotBefor token生效时间
                    new Claim(JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddMilliseconds(1)).ToUnixTimeSeconds()}") //Expiration 到期时间，按秒数算
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("0123456789xyzabcdefg"));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    issuer: "http://localhost:5000",
                    audience: "http://localhost:5000",
                    claims:claims,
                    expires:DateTime.Now.AddMinutes(5),
                    signingCredentials:creds);
                return Ok(new { 
                token=new JwtSecurityTokenHandler().WriteToken(token),
                expiration=token.ValidTo
                } );
            }
            else
            {
                return BadRequest(ResultModel.Fail(0, "登录失败，请重试"));
            }
        }
        /// <summary>
        /// 获取token中附加的当前用户
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("/api/account/GetCurrentUser")]
        public IActionResult GetCurrentUser()
        {
            return Ok("name:" + User.Identity.Name + "," + "role:" + User.Claims.Where(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").FirstOrDefault().Value + ",grade:" + User.Claims.Where(x => x.Type == "grade").FirstOrDefault().Value);
        }
    }
}
